import os
import sys
import requests

from flask import Flask, send_file, make_response

if __name__ != '__main__':
  sys.path.append(os.getcwd())

from keen import FileMap, ServerCipher, FileServer

file_map = FileMap()
cipher = ServerCipher()

# root_path_env = os.environ.get('KEEN_FILE')
# FileServer.root_path = root_path_env or '/keen-file'

app = Flask(__name__, instance_relative_config=True)

@app.route('/get-dev/<path:fpath>')
def get_dev(fpath):
  env = os.environ.get('FLASK_ENV')
  if env != 'development':
      return('', 400)
  path = os.path.abspath(os.path.join(os.getcwd(), fpath))
  response = make_response(send_file(path))
  return response

@app.route('/r-add/<path:fpath>')
def r_add(fpath):
  full_path = cipher.decipher(fpath)
  print('[r_add]', full_path)
  return file_map.add(full_path)

@app.route('/r/<hash>/<name>')
def r(hash, name):
  full_path = file_map.get(hash)
  if full_path is None:
    # return ('', 404)
    return file_map.test()
  response = make_response(send_file(full_path))
  return response

if __name__ == '__main__':
  app.run('127.0.0.1', port=30002)